package com.eregg.learn.netty.protocol.server.handler;

import com.eregg.learn.netty.protocol.attribute.Attributes;
import com.eregg.learn.netty.protocol.protocol.request.MessageRequestPacket;
import com.eregg.learn.netty.protocol.protocol.response.MessageResponsePacket;
import com.eregg.learn.netty.protocol.session.Session;
import com.eregg.learn.netty.protocol.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) throws Exception {
        //1. 获取发送人信息
        Session user = ctx.channel().attr(Attributes.SESSION).get();
        //2. 构造响应信息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(user.getUserId());
        messageResponsePacket.setFromUsername(user.getUsername());
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());
        //3. 获取接收方Channel
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());
        if(toUserChannel != null && SessionUtil.hasLogin(toUserChannel)){
            //4. 将消息发送给接收方
            toUserChannel.writeAndFlush(messageResponsePacket);
        }else {
            System.out.println("用户不在线发送失败");
        }

    }
}
